package com.operation;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.NotFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ScriptTag;
import org.htmlparser.util.NodeList;
import org.mk.HibernateException;
import org.mk.type.MySQLTypeFactory;
import org.mk.type.Type;

import com.db.ColumnInfoBean;
import com.db.ForeignKey;
import com.db.connection.DBCPPostgresManager;
import com.excel.read.Config;
import com.excel.read.DBTable;
import com.operation.model.OperationModel;
import com.service.ImportService;
import com.xml.Record;
import com.xml.RecordExtract;
import com.xml.SQLparam;

/**
 * 记录同步
 * 
 * @author mike
 * 
 */
public class RecordOperation {
	public static Log log = LogFactory.getLog(RecordOperation.class);

	public static void insert(List<OperationModel> list, Connection conn)
			throws HibernateException, SQLException {
		for (OperationModel opMap : list) {
			opMap.insert(conn);
		}

	}

	public static void insertBantch(List<OperationModel> list, Connection conn)
			throws HibernateException, SQLException {
		for (OperationModel opMap : list) {
			opMap.insert(conn);
		}

	}

	/**
	 * 取得下一个主键值
	 * 
	 * @param dbTable
	 * @return
	 */
	public static long getNextPK(DBTable dbTable) {
		ColumnInfoBean pk = dbTable.getPk();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {

			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn.prepareStatement("select max(" + pk.getName()
					+ ") from " + dbTable.getName());

			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getLong(1);
			}
		} catch (Exception ex) {
			log.error("Error : " + ex.toString());
		} finally {
			try {
				rs.close();
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return 0;
	}

	/**
	 * 根据业务主键取得自然主键
	 * 
	 * @param aForeignKey
	 * @return
	 */
	public static String getQueryID(ForeignKey aForeignKey) {
		StringBuffer sbf = new StringBuffer();
		sbf.append("select ");
		sbf.append(aForeignKey.getToTable().getPk().getName());
		sbf.append(" from ");
		sbf.append(aForeignKey.getToTable().getName());
		sbf.append(" where ");
		List<ColumnInfoBean> realPKs = aForeignKey.getToTable().realPK;
		boolean flag = true;
		for (ColumnInfoBean rpk : realPKs) {
			if (flag) {
				flag = !flag;
				sbf.append(rpk.getName());
				sbf.append(" = ? ");
			} else {
				sbf.append(" and ");
				sbf.append(rpk.getName());
				sbf.append(" = ?");
			}
		}

		return sbf.toString();
	}

	/**
	 * 取得自然主键和业务逐渐值对
	 * 
	 * @param aForeignKey
	 * @return
	 */
	public static String getQueryIDValue(ForeignKey aForeignKey) {
		StringBuffer sbf = new StringBuffer();
		sbf.append("select ");
		String pkName = aForeignKey.getToTable().getPk().getName();
		sbf.append(pkName);
		for (ColumnInfoBean cinfo : aForeignKey.getToTable().realPK) {
			if (!pkName.equalsIgnoreCase(cinfo.getName())) {
				sbf.append(", ");
				sbf.append(cinfo.getName());
			}
		}

		sbf.append(" from ");
		sbf.append(aForeignKey.getToTable().getName());
		sbf.append(" where ");
		boolean flag = true;
		// for(ColumnInfoBean cinfo : aForeignKey.getToTable().realPK) {
		// if(flag) {
		// flag = !flag;
		// sbf.append(cinfo.getName());
		// sbf.append(" = ?");
		// }else {
		// sbf.append(" and ");
		// sbf.append(cinfo.getName());
		// sbf.append(" = ?");
		// }
		//			
		// }

		sbf.append(aForeignKey.getToTable().getPk().getName());
		sbf.append(" = ? ");
		return sbf.toString();
	}

	/**
	 * 根据本地业务主键取得本地自然主键（用于同步服务）
	 * 
	 * @return
	 */
	public static long getPKByRPK(String sql, List<Type> types,
			List<Object> values) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {

			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; i < types.size(); i++) {
				Type type = types.get(i);
				type.nullSafeSet(pstmt, values.get(i), i + 1);
			}
			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getLong(1);
			}
		} catch (Exception ex) {
			log.error("Error : " + ex.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return 0;
	}

	/**
	 * 根据refpk表取得新主键，用于外键查询
	 * 
	 * @param sql
	 * @param types
	 * @param values
	 * @return select pk_client from refpk where org_id= ? and table_name = ?
	 *         and pk = ?
	 */
	public static long getPKByRPK2(long orgId, String tableName, long pk) {
		String sql = "select pk_client from refpk where org_id= ? and table_name = ? and pk = ?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {

			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn.prepareStatement(sql);
			pstmt.setLong(1, orgId);
			pstmt.setString(2, tableName);
			pstmt.setLong(3, pk);

			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getLong(1);
			}
		} catch (Exception ex) {
			log.error("Error : " + ex.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return 0;
	}

	/**
	 * 根据本地自然主键取得自然主键，和业务主键值对
	 * 
	 * @return
	 */
	public static List<Record> getPKValue(String tableName,
			List<String> fields, String sql, Type type, Object value) {
		List<Record> aList = new ArrayList<Record>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {

			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn.prepareStatement(sql);
			type.nullSafeSet(pstmt, value, 1);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				Record aRecord = new Record();
				aRecord.setTableName(tableName);
				for (String fieldName : fields) {
					Object aValue = type.nullSafeGet(rs, fieldName, null);
					aRecord.put(fieldName, aValue);
				}
				aList.add(aRecord);
				return aList;
			}
		} catch (Exception ex) {

			log.error("Error : getPKValue" + ex.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);
		}
		return aList;
	}

}
